//
//  RBHistoryVC.m
//  zhongzhenglu
//
//  Created by XL on 2022/7/15.
//

#import "RBHistoryVC.h"
#import <UIColor+YYAdd.h>
#import "RBThemeConfig.h"
#import <UIControl+YYAdd.h>
#import "UIView+RBAdd.h"
#import "RBDefine.h"
#import <Masonry.h>
#import "UIButton+RBAdd.h"
#import "RBHistoryCell.h"
#import "RBHistoryDateHeader.h"
#import "RBRefreshHeader.h"
#import "RBRefreshFooter.h"
#import "UIViewController+RBAdd.h"
#import "RBGoodsDetailVC.h" //商品详情

@interface RBHistoryVC ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong) RBHistoryResponse *response;

@end

@implementation RBHistoryVC

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
    [self.listView.mj_header beginRefreshing];
}

#pragma mark - Private

- (void)setup
{
    self.title = @"我的足迹";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem.alloc initWithTitle:@"清空" style:UIBarButtonItemStylePlain target:self action:@selector(clearBtnTapped)];
    self.view.backgroundColor = [RBThemeConfig bgGrayColor];
}

- (void)fillData
{
    for (RBHistoryModel *model in self.response.data)
    {
        RBGroupModel *lastGroup = self.dataSource.count? self.dataSource.lastObject: nil;
        if(![lastGroup.exStr isEqualToString:model.dateStr])
        {
            lastGroup = RBGroupModel.new;
            [self.dataSource addObject:lastGroup];
            lastGroup.exStr = model.dateStr;
            lastGroup.headerView = ({
                RBHistoryDateHeader *view = RBHistoryDateHeader.new;
                view.text = lastGroup.exStr;
                view;
            });
            lastGroup.headerHeight = Zoom(50);
            lastGroup.cellModels = NSMutableArray.array;
        }
        NSMutableArray *arrayM = (NSMutableArray *)lastGroup.cellModels;
        [arrayM addObject:({
            RBCellModel *cellModel = RBCellModel.new;
            cellModel.reuseCellIdentifier = NSStringFromClass(RBHistoryCell.class);
            cellModel.cellSelectBlock = ^(NSIndexPath *indexPath) {
                RBGoodsDetailVC *vc = [RBGoodsDetailVC new];
                vc.id = model.good_id;
                [self.navigationController pushViewController:vc animated:YES];
            };
            cellModel.cellData = model;
            cellModel;
        })];
    }
    [self.tableView reloadData];
    if(!self.dataSource.count)
    {
        [self.listView showPlaceHolder:RB_EMPTY_TIP tapBlock:nil];
    }
}

#pragma mark - Network

- (NSString *)listPageKey
{
    return @"page";
}
- (NSDictionary *)listParams
{
    NSMutableDictionary *dicM = NSMutableDictionary.dictionary;
    return dicM;
}
- (NSString *)listRequestPath
{
    return @"hu_footprint";
}
- (NSInteger)ListCurrentPage
{
    return self.response.currentPage;
}
- (BOOL)listLog
{
    return YES;
}
- (BOOL)listPost
{
    return YES;
}
- (Class)listResponseClass
{
    return RBHistoryResponse.class;
}
- (UIScrollView *)listView
{
    return self.tableView;
}

- (void)getFirstPageData
{
    __weak typeof(self) weak_self = self;
    [self listLoadFirstPageWithDesView:self.listView showPlaceHolder:YES sucBlock:^(id data) {
        weak_self.response = data;
        [weak_self.dataSource removeAllObjects];
        [weak_self fillData];
    } failBlock:^(id data) {
        
    } reloadBlock:^{
        [weak_self getFirstPageData];
    }];
}

- (void)getNextPageData
{
    __weak typeof(self) weak_self = self;
    [self listLoadNextPageWithSucBlock:^(id data) {
        weak_self.response = data;
        [weak_self fillData];
    } failBlock:^(id data) {
        
    }];
}

- (void)deleteRequestWithIndexPath:(NSIndexPath *)indexPath
{
    RBHistoryModel *model = [RanTool modelWithSection:indexPath.section row:indexPath.row dataSource:self.dataSource];
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"foot_id"] = model.foot_id;
    } path:@"hu_footprint_del" post:YES log:YES responseClass:RBResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(id data) {
        [RanTool removeModel:model dataSource:weak_self.dataSource];
        RBGroupModel *group = weak_self.dataSource[indexPath.section];
        if(group.cellModels.count)
        {
            [weak_self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        else
        {
            [weak_self.dataSource removeObject:group];
            [weak_self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
            if(!weak_self.dataSource.count)
            {
                [weak_self.listView.mj_header beginRefreshing];
            }
        }
    } failBlock:^(RBResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}

- (void)clearRequest
{
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        
    } path:@"hu_footprint_del_all" post:YES log:YES responseClass:RBResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(id data) {
        [weak_self.listView.mj_header beginRefreshing];
    } failBlock:^(RBResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}

#pragma mark - Event

- (void)clearBtnTapped
{
    if(!self.dataSource.count)
    {
        [self.view showTip:@"暂无数据" completion:nil];
        return;
    }
    __weak typeof(self) weak_self = self;
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"是否清空数据" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [vc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [vc addAction:[UIAlertAction actionWithTitle:@"清空" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [weak_self clearRequest];
    }]];
    [self presentViewController:vc animated:YES completion:nil];

}

#pragma mark - UITableViewDataSource & Delegate

kRBTableViewDataSourceAndDelegate(self.dataSource);

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weak_self = self;
    return @[[UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [weak_self deleteRequestWithIndexPath:indexPath];
    }]];
}

#pragma mark - Setter

#pragma mark - Getter

- (UITableView *)tableView
{
    if (!_tableView)
    {
        self.tableView = ({
            UITableView *view = [UITableView.alloc initWithFrame:CGRectZero style:UITableViewStylePlain];
            view.dataSource = self;
            view.delegate = self;
            view.showsVerticalScrollIndicator = NO;
            view.showsHorizontalScrollIndicator = NO;
            kRBIgnoreScrollViewInsetsAdjust(view);
            view.separatorStyle = UITableViewCellSeparatorStyleNone;
            view.tableFooterView = UIView.new;
            view.backgroundColor = UIColor.clearColor;
            view.estimatedRowHeight = UITableViewAutomaticDimension;
            view.mj_header = [RBRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(getFirstPageData)];
            view.mj_footer = [RBRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(getNextPageData)];

            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(0);
                make.top.mas_equalTo(0);
            }];
            view;
        });
    }
    return _tableView;
}

- (NSMutableArray *)dataSource
{
    if (!_dataSource)
    {
        self.dataSource = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            arrayM;
        });
    }
    return _dataSource;
}

@end
